'''
Created on 2011-3-13

@author: Frank F Zhang
'''
from django import forms
from django.contrib.auth.models import User
from django.utils.translation import ugettext_lazy as _

class UserSignupForm(forms.Form):
    MAX_LENGTH = 10
    """
    A form that creates a user with profile
    """
    email = forms.EmailField(label=_("Email"),
        help_text = _("Required. 10 characters or fewer. Alphanumeric characters only (letters, digits and underscores)."),
        widget = forms.TextInput(attrs={"class":"text-field"}))
    
    password1 = forms.CharField(label=_("Password"),
        max_length=20, 
        widget=forms.PasswordInput(attrs={"class":"text-field"}),
        help_text = _("20 character maximum; case sensitive."))
    
    password2 = forms.CharField(label=_("Confirm password"),
        max_length=20,
        widget=forms.PasswordInput(attrs={"class":"text-field"}),
        help_text = _("Please type the password again."))
    
    firstname = forms.CharField(label=_("First name"),
		max_length=20,
		widget = forms.TextInput(attrs={"class":"text-field"}))
    
    lastname = forms.CharField(label=_("Last name"),
		max_length=20,
		widget = forms.TextInput(attrs={"class":"text-field"}))
    
    def clean_email(self):
        """
        Validate that the supplied email address is unique for the
        site.
        """
        if User.objects.filter(email__iexact=self.cleaned_data['email']).count():
            raise forms.ValidationError(_(u'This email address is already in use. Please supply a different email address.'))
        return self.cleaned_data['email']
    
    def clean_password2(self):
        """
        Validate that the two password match each other.
        """
        password1 = self.cleaned_data["password1"]
        password2 = self.cleaned_data["password2"]
        if password1 != password2:
            raise forms.ValidationError(_("The two password fields didn't match."))
        return password2
        
class UserLoginForm(forms.Form):
    username = forms.CharField(label=_("Username"),
        widget = forms.TextInput(attrs={"class":"text-field"}))
    
    password = forms.CharField(label=_("Password"), 
        max_length=20,
        widget=forms.PasswordInput(attrs={"class":"text-field"}))
    
    user = None
    
    def clean(self):
        cleaned_data = self.cleaned_data
        username = cleaned_data["username"]
        password = cleaned_data["password"]
        from django.contrib.auth import authenticate
        self.user = authenticate(username=username, password=password)
        if self.user is None:
            self._errors["password"] = forms.util.ErrorList([_("Failed to login using this username and password.")])
        return cleaned_data